<template>
  <div class="user-manage">
    <!-- 顶部搜索栏 -->
    <el-card>
      <div class="query-form">
        <el-form ref="FormRef" :inline="true" :model="user">
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="user.userId" placeholder="请输入用户ID" />
          </el-form-item>
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="user.userName" placeholder="请输入用户名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset('FormRef')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <div class="base-table">
        <div class="action">
          <el-button type="primary" @click="handleCreate">新增</el-button>
          <el-button type="danger">批量删除</el-button>
          <el-button class="ref" @click="handleRefresh">刷新</el-button>
        </div>
        <el-table border :data="userList" style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="item in columns"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :formatter="item.formatter"
          ></el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                >编辑</el-button
              >
              <el-button @click="handleDel(scope.row)" type="danger" size="mini"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          class="pagination"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑弹框 -->
    <el-dialog width="35%" title="用户新增" v-model="showModal">
      <el-form
        ref="dialogForm"
        :model="userForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="userForm.userName"
            :disabled="action == ''"
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            v-model="userForm.userEmail"
            :disabled="action == ''"
            placeholder="请输入用户邮箱"
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-input
            v-model="userForm.role"
            :disabled="action == 'add'"
            placeholder="请输入用户角色"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref, toRaw } from "vue";
import { getUserList, userSubmit, userDelete } from "../../api/index";
import utils from "../../utils/utils";

// const FormRef = ref("");
// 获取Composition API 上下文对象
const { proxy } = getCurrentInstance();
// 初始化用户表单对象
const user = reactive({
  userId: "",
  userName: "",
});
// const ruleFormRef = ref(null);
// 初始化用户列表数据
const userList = ref([]);
// 初始化分页对象
const pager = reactive({
  total: 5,
  pageNum: 1,
  pageSize: 5,
});
// 选中用户列表对象
const checkedUserIds = ref([]);
// 弹框显示对象
const showModal = ref(false);
// 新增用户Form对象
const userForm = reactive({
  action: "",
  userName: "",
  userEmail: "",
  role: "1",
  userId: "",
});
// 定义用户操作行为
const action = ref("add");
// 定义表单校验规则
const rules = reactive({
  userName: [
    {
      required: true,
      message: "请输入用户名称",
      trigger: "blur",
    },
  ],
  userEmail: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
  ],
});
// 定义动态表格-格式
const columns = reactive([
  {
    label: "用户ID",
    prop: "userId",
    width: 100,
  },
  {
    label: "用户名",
    prop: "userName",
    width: 100,
  },
  {
    label: "用户邮箱",
    prop: "userEmail",
    width: 180,
  },
  {
    label: "用户角色",
    prop: "role",
    formatter(row, column, value) {
      return {
        0: "管理员",
        1: "普通用户",
      }[value];
    },
  },
  {
    label: "注册时间",
    prop: "createTime",
    width: 180,
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "最后登录时间",
    prop: "lastLoginTime",
    width: 180,
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
]);
// 用户弹窗关闭
const handleClose = () => {
  showModal.value = false;
  handleReset("dialogForm");
};
// 用户新增
const handleCreate = () => {
  action.value = "add";
  showModal.value = true;
};
// 用户新增、编辑提交
const handleSubmit = () => {
  proxy.$refs.dialogForm.validate(async (valid) => {
    if (valid) {
      let params = toRaw(userForm);
      params.action = action.value;
      console.log(params);
      await userSubmit(params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          showModal.value = false;
          proxy.$message.success(res.msg);
          handleReset("dialogForm");
          getuserlist();
        }
      });
    }
  });
};
// 用户编辑
const handleEdit = (row) => {
  // console.log(row);
  action.value = "edit";
  showModal.value = true;
  proxy.$nextTick(() => {
    Object.assign(userForm, row);
  });
};
// 删除
const handleDel = async (row) => {
  let id = row.userId;
  await proxy.userDelete({ userIds: id }).then((res) => {
    if (res.code == 200) {
      proxy.$message.success("删除成功");
      getuserlist();
    } else {
      proxy.$message.error("删除成功");
    }
  });
};
// 重置
const handleReset = (form) => {
  console.log(form);
  proxy.$refs[form].resetFields();
};
// 查询
const handleQuery = () => {
  getuserlist();
};
// 获取数据集合
const getuserlist = async () => {
  let params = user;
  console.log(params);
  await getUserList(params).then((res) => {
    // console.log(res);
    userList.value = res;
  });
};
//挂载页面
onMounted(() => {
  getuserlist();
});
</script>

<style lang="scss" scoped>
::v-deep .el-card {
  margin: 5px 0 25px 0;
}
.ref {
  float: right;
}
.action {
  margin-bottom: 30px;
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
